package com.zm.common.core.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * FileUtils
 * 
 * @author DENG.ZHUO.HUI
 * @email 13751827792@163.com
 * @date 2017年3月10日
 * @version 1.0
 */
public class FileUtils {

	public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
		System.out.println("=============== zipFiles ===================");
		try {
			int size = files.size();
			// 压缩列表中的文件
			for (int i = 0; i < size; i++) {
				File file = (File) files.get(i);
				System.out.println(file.getPath());
				zipFile(file, outputStream);
			}
		} catch (IOException e) {
			throw e;
		}
	}

	public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
		System.out.println("======================== zipFile ===================");
		try {
			if (inputFile.exists()) {
				if (inputFile.isFile()) {
					FileInputStream inStream = new FileInputStream(inputFile);
					BufferedInputStream bInStream = new BufferedInputStream(inStream);
					ZipEntry entry = new ZipEntry(inputFile.getName());
					try {
						outputstream.putNextEntry(entry);
					} catch (ZipException e) {
						entry = new ZipEntry(UUID.randomUUID().toString() + inputFile.getName().substring(inputFile.getName().lastIndexOf(".")));
						outputstream.putNextEntry(entry);
						e.printStackTrace();
					}

					final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
					long streamTotal = 0; // 接受流的容量
					int streamNum = 0; // 流需要分开的数量
					int leaveByte = 0; // 文件剩下的字符数
					byte[] inOutbyte; // byte数组接受文件的数据

					streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
					streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
					leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

					if (streamNum > 0) {
						for (int j = 0; j < streamNum; ++j) {
							inOutbyte = new byte[MAX_BYTE];
							// 读入流,保存在byte数组
							bInStream.read(inOutbyte, 0, MAX_BYTE);
							outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
						}
					}
					// 写出剩下的流数据
					inOutbyte = new byte[leaveByte];
					bInStream.read(inOutbyte, 0, leaveByte);
					outputstream.write(inOutbyte);
					outputstream.closeEntry(); // Closes the current ZIP entry
					// and positions the stream for
					// writing the next entry
					bInStream.close(); // 关闭
					inStream.close();
					System.out.println("======================== ziped ===================");
				}
			} else {
				throw new ServletException("文件不存在！");
			}
		} catch (IOException e) {
			throw e;
		}
	}

	public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response,
			boolean isDelete) {
		System.out.println(file.getPath());
		try {
			// 以流的形式下载文件。
			/*BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			//response.reset();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());*/
//			response.setContentType("application/octet-stream");
			
			
			response.setContentType("multipart/form-data"); 

			String fileFullName = file.getName();
			String suffix = fileFullName.substring(fileFullName.lastIndexOf("."));
			String fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
			String userAgent = request.getHeader("user-agent");
			System.out.println(userAgent);
			if (userAgent.toLowerCase().indexOf("msie") != -1) {
				fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
			} else if (userAgent.toLowerCase().indexOf("firefox") != -1) {
				fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, "utf-8");
			}

			System.out.println(fileName+suffix);
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + suffix);
			
			FileInputStream fis = new FileInputStream(file);
			ServletOutputStream os = response.getOutputStream();
			int len = 0;
			byte[] arr = new byte[8 * 1024];
			while( (len = fis.read(arr)) != -1 ){
				os.write(arr,0,len);
			}
			fis.close();
			os.close();
			
			/*toClient.write(buffer);
			toClient.flush();
			toClient.close();*/
			if (isDelete) {
				file.delete(); // 是否将生成的服务器端文件删除
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}
